package Work0604;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Scanner;

/**
 * 3：实现文件加密解密：加密规则是读出每一个字节，取反(~)后，写入 新文件，然后删除原文件，把新文件改成原文件同名的文件，
 * 解密规则类似。输入一个文件名，实现加密和解密功能
 * 
 * @author Y
 *
 */
public class EncryptionDecryption {
	/**
	 * 加密
	 * 
	 * @param args
	 * @throws Exception
	 */
	public static void main(String[] args) throws Exception {
		// 加密
		Scanner in = new Scanner(System.in);
		System.out.println("输入一个文件:");
		String test = in.next();
		File file = new File(test);// 源文件
		File file2 = new File("C:\\Users\\Y\\Desktop\\北大青鸟课件\\北大青鸟作业\\12345.txt");// 新文件
		InputStream a = new FileInputStream(file);
		OutputStream p = new FileOutputStream(file2);
		byte[] b = new byte[a.available()];
		int q = a.read(b);
		for (int c = 0; c < b.length; c++) {
			p.write(~b[c]);// 取反并写入新文件
		}
		a.close();
		p.close();
		file.delete();// 删除源文件
		file2.renameTo(new File(test));// 改名

		System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
		// 解密
		File t = new File(test);
		File t1 = new File("C:\\Users\\Y\\Desktop\\北大青鸟课件\\北大青鸟作业\\12345.txt");
		InputStream a1 = new FileInputStream(t);
		OutputStream p1 = new FileOutputStream(t1);
		byte[] b1 = new byte[a1.available()];
		int q1 = a1.read(b1);
		for (int c1 = 0; c1 < b1.length; c1++) {
			p1.write(~b1[c1]);
		}
		a1.close();
		p1.close();
		t.delete();
		t1.renameTo(new File(test));
	}

}
